//
//  MCOrderDetailSuccessfulDealViewController.swift
//  StoreManage
//
//  Created by MC on 2017/12/21.
//  Copyright © 2017年 MC. All rights reserved.
//

import UIKit

class MCAfterSaleDetailViewController: MCViewController {
    
    var model : MCAfterSaleListModel = MCAfterSaleListModel()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
        
        sendNetworking()
    }
    
    // MARK: - System Delegate
    
    // MARK: - Custom Delegate
    
    // MARK: - Action
    @objc func refuseReasonSaveEvent() {
        refuseReasonView.removeFromSuperview()
        MCAfterOrdderWaitDealWithStatus_refused(type: 2, storeRefuseReason: refuseReasonView.textView.text)
    }

    
    @objc func leftButtonClicked() {
        switch model.status {
        case 1:  // 待处理的拒绝事件
            self.view.window?.addSubview(refuseReasonView)
            refuseReasonView.snp.remakeConstraints { (make) ->Void in
                make.edges.equalTo(self.view.window!)
            }
        case 2:
            if model.isRefund == 1 || model.sendBack == 2 { // 待退款的确认退款
                MCAfterOrdderWaitBackMoneyStatus_sureBackMoney()
            } else {  // 待退货的拒绝
                self.view.window?.addSubview(refuseReasonView)
                refuseReasonView.snp.remakeConstraints { (make) ->Void in
                    make.edges.equalTo(self.view.window!)
                }
            }
        default:
            break
        }
    }
    
    
    @objc func rightButtonClicked() {
        switch model.status {
        case 1:  // 待处理的同意事件
            MCAfterOrdderWaitDealWithStatus_refused(type: 1, storeRefuseReason: "")
        case 2:
            if model.isRefund == 2 { // 待退货状态的确认收到用户的退货商品
            }
        default: // 待退货同意
            MCAfterOrdderWaitDealWithStatus_refused(type: 3, storeRefuseReason: "")
            break
        }
    }

    
    func MCAfterOrdderWaitDealWithStatus_refused(type:Int,storeRefuseReason:String) {
        
        let para = [
            "afterSalesId" : model.afterSalesId,
            "type"         : type,  // 1同意售后2拒绝售后
            "storeRefuseReason" : storeRefuseReason,
            "mallStoreId"  : MCUserinfo_getStoreId()
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_storeAfterSalesOption, para: para as [String : AnyObject], vc: self,hudSuperView: self.view,isHiddenTabbar: true, success: { (response) in

            if type == 1 {
                MCHUD_text(message: "已经同意", view: self.view, delay: 1.2)
            } else {
                MCHUD_text(message: "已经拒绝", view: self.view, delay: 1.2)
            }
            
            
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.2, execute: {
                self.navigationController?.popViewController(animated: true)
            })
            
        }, dislike: { (response) in }) { (error) in }
    }
    

    // 待退款的确认退款网络请求
    func MCAfterOrdderWaitBackMoneyStatus_sureBackMoney() {
        let para = [
            "afterSn" : model.afterSn,
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_storeRefund, para: para as [String : AnyObject], vc: self,hudSuperView: self.view,isHiddenTabbar: true, success: { (response) in
            MCHUD_text(message: "已经同意该单的退款", view: self.view, delay: 1.2)
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.2, execute: {
                self.navigationController?.popViewController(animated: true)
            })

        }, dislike: { (response) in }) { (error) in }
    }

    
    // MARK: - Network
    func sendNetworking() {
        let para = [
            "afterSalesId" : model.afterSalesId,
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_getAfterSalesDetail, para: para as [String : AnyObject], vc: self,hudSuperView: self.view,isHiddenTabbar: true, success: { (response) in
            let dataDict = response["data"] as! [String : AnyObject]
            
            let createTime = dataDict["createTime"] as? String ?? ""
            let isRefund = dataDict["isRefund"] as? Int ?? 0 //1仅退款2退货退款
            let userRefundReason = dataDict["userRefundReason"] as? String ?? "" // 退款原因
            let userFirstReason = dataDict["userFirstReason"] as? String ?? ""  //退款说明
            let imgProof1 = dataDict["imgProof1"] as? String ?? ""
            let imgProof2 = dataDict["imgProof2"] as? String ?? ""
            let imgProof3 = dataDict["imgProof3"] as? String ?? ""

            let arrayM = NSMutableArray()
            if imgProof1.count > 0 {
                arrayM.add(imgProof1)
            }
            if imgProof2.count > 0 {
                arrayM.add(imgProof2)
            }
            if imgProof3.count > 0 {
                arrayM.add(imgProof3)
            }
            
            let storeRefuseReason = dataDict["storeRefuseReason"] as? String ?? ""  // 门店拒绝理由
            var courierNumber = dataDict["courierNumber"] as? String ?? ""
            if courierNumber.count == 0 {
                courierNumber = "暂无"
            }
            
            self.footerView.timeView.detailLabel.text = createTime.MCString_prefix(index: 16)
            if isRefund == 1 {
                self.footerView.typeView.detailLabel.text = "仅退款"
            } else {
                 self.footerView.typeView.detailLabel.text = "退货退款"
            }
            self.footerView.reasonView.detailLabel.text = userRefundReason
            self.footerView.explainView.detailLabel.text = userFirstReason
            self.footerView.imageArray = arrayM
            self.footerView.refuseView.detailLabel.text = storeRefuseReason
            self.footerView.logisticsView.detailLabel.text = courierNumber
        }, dislike: { (response) in }) { (error) in }
    }
    
    // MARK: - Method
    func baseSetting() {
        self.title =  "订单详情"
        self.view.backgroundColor = UIColor.white
    }
    
    func initUI() {
        
        var bottomViewHeight : CGFloat = 0
        
        

        
        switch model.status {
        case 1:   // 待处理
            bottomViewHeight = 50
            bottomView.leftButton.setTitle("拒绝", for: UIControlState.normal)
            bottomView.rightButton.setTitle("同意", for: UIControlState.normal)
            bottomView.isOnlyOne = false
        case 2:   // 待退款
            
            if model.isRefund == 1 || model.sendBack == 2 {  // 待退款
                bottomView.isOnlyOne = true
                bottomView.leftButton.setTitle("确认退款", for: UIControlState.normal)
            } else {   // 待退货
                bottomView.isOnlyOne = false
                bottomView.leftButton.setTitle("拒绝", for: UIControlState.normal)
                bottomView.rightButton.setTitle("确认收到退货", for: UIControlState.normal)
            }
            
            bottomViewHeight = 50
        case 4:   // 已拒绝
            bottomViewHeight = 0
        case 3:   // 已完成
            bottomViewHeight = 0
        default: // 待退货
            bottomView.leftButton.setTitle("拒绝", for: UIControlState.normal)
            bottomView.rightButton.setTitle("确认退货", for: UIControlState.normal)
            bottomView.isOnlyOne = false
            break
        }
        view.addSubview(bottomView)
        bottomView.snp.remakeConstraints { (make) ->Void in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(bottomViewHeight)
        }
        view.addSubview(tableView)
        tableView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view).inset(UIEdgeInsetsMake(0, 0, bottomViewHeight, 0))
        }
        tableView.tableFooterView = footerView

    }
    
    // MARK: - Setter & Getter
    lazy private var tableView: MCTableView = {
        let tableView = MCTableView.init(frame: CGRect.zero, style: UITableViewStyle.plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.MCGray_light
        return tableView
    }()
    
    lazy var footerView: MCAfterSaleDetailFooterView = {
        let view = MCAfterSaleDetailFooterView()
        view.model = model
        view.tableView = self.tableView
        return view
    }()
    
    
    lazy var bottomView: MCAfterSaleDetailBottomView = {
        let view = MCAfterSaleDetailBottomView()
        view.leftButton.addTarget(self, action: #selector(leftButtonClicked), for: UIControlEvents.touchUpInside)
        view.rightButton.addTarget(self, action: #selector(rightButtonClicked), for: UIControlEvents.touchUpInside)
        return view
    }()
    
    lazy var refuseReasonView: MCAfterSaleDetailWriteRefuseReasonView = {
        let view = MCAfterSaleDetailWriteRefuseReasonView()
        view.saveButton.addTarget(self, action: #selector(refuseReasonSaveEvent), for: UIControlEvents.touchUpInside)
        return view
    }()
}

extension MCAfterSaleDetailViewController : UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 185
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = MCAfterSaleListCell.init(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")
        
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        
        cell.model = model
        
        return cell
    }
}






